package com.innovation.ic.cyz.base.service.cyz.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.innovation.ic.cyz.base.mapper.cyz.BannerMapper;
import com.innovation.ic.cyz.base.model.cyz.Banner;
import com.innovation.ic.cyz.base.pojo.global.ApiResult;
import com.innovation.ic.cyz.base.pojo.global.ServiceResult;
import com.innovation.ic.cyz.base.pojo.constant.FtpModule;
import com.innovation.ic.cyz.base.pojo.variable.cyz.banner.BannerAvailableDataRespPojo;
import com.innovation.ic.cyz.base.service.cyz.BannerService;
import com.innovation.ic.cyz.base.value.config.FtpAccountConfig;
import com.innovation.ic.cyz.base.vo.cyz.BennerVo;
import com.jcraft.jsch.SftpException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class BannerServiceImpl extends ServiceImpl<BannerMapper, Banner> implements BannerService {
    private static final Logger log = LoggerFactory.getLogger(BannerServiceImpl.class);

    @Resource
    private FtpAccountConfig ftpAccountConfig;

    @Resource
    private BannerMapper bannerMapper;

    /**
     * 获取启用的轮播图数据
     * @return 返回查询结果
     */
    @Override
    public ServiceResult<List<BannerAvailableDataRespPojo>> getAvailableBannerList() {
        List<BannerAvailableDataRespPojo> result = bannerMapper.getAvailableBannerList();

        ServiceResult<List<BannerAvailableDataRespPojo>> serviceResult = new ServiceResult<>();
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setResult(result);
        return serviceResult;
    }

    /**
     * 通过id查询banner数据
     * @param bennerVo
     * @return 返回查询结果
     */
    @Override
    public ServiceResult<Banner> selectIdBannner(BennerVo bennerVo){
        ServiceResult<Banner> listServiceResult = new ServiceResult<>();
        Banner banner = bannerMapper.selectById(bennerVo.getId());
        listServiceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        listServiceResult.setSuccess(Boolean.TRUE);
        listServiceResult.setResult(banner);
        return listServiceResult;
    }

    /**
     * Bannner列表
     * @param bennerVo
     * @return
     */
    @Override
    public ServiceResult<List<Banner>> allBanner(BennerVo bennerVo) {
        ServiceResult<List<Banner>> listServiceResult = new ServiceResult<>();
        Integer pageNo = (bennerVo.getPageNo() - 1) * bennerVo.getPageSize();
        Integer pageSize = bennerVo.getPageSize();
        List<Banner> list = bannerMapper.allBanner(pageNo, pageSize);
        for (Banner banner : list) {
            banner.setPicture(banner.getPicturePath());
        }
        listServiceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        listServiceResult.setSuccess(Boolean.TRUE);
        listServiceResult.setResult(list);
        return listServiceResult;
    }

    /**
     * 添加Bannner
     * @param bennerVo
     * @return
     */
    @Override
    public ServiceResult<ApiResult<Boolean>> addBannner(BennerVo bennerVo) throws IOException, SftpException {
        ServiceResult<ApiResult<Boolean>> apiResultServiceResult = new ServiceResult<>();
        String type = FtpModule.FTP_ADD;
//        UploadVideoPojo uploadVideoPojo = ftpImg(type, bennerVo);
        Banner benner = new Banner();
        benner.setName(bennerVo.getName());//名称
        benner.setPicturePath(bennerVo.getPicturePath());//图片路径
        benner.setSize(bennerVo.getSize());//尺寸
        benner.setAvailable(bennerVo.getAvailable());//状态
//        benner.setSecondaryPagePath(bennerVo.getSecondaryPagePath());//二级页面目录
        benner.setCreatorId(bennerVo.getCreatorId());//创建人id
        benner.setCreateTime(new Date());
        bannerMapper.insert(benner);
        apiResultServiceResult.setSuccess(Boolean.TRUE);
        apiResultServiceResult.setMessage(ServiceResult.INSERT_SUCCESS);
        return apiResultServiceResult;
    }

    /**
     * 编辑Banner
     * @param bennerVo
     * @return
     */
    @Override
    public ServiceResult<ApiResult<Boolean>> updateBanner(BennerVo bennerVo) throws IOException, SftpException {
        ServiceResult<ApiResult<Boolean>> apiResultServiceResult = new ServiceResult<>();
//        String type = FtpModule.FTP_UPDATE;
//        UploadVideoPojo uploadVideoPojo = ftpImg(type, bennerVo);
//        if (uploadVideoPojo == null) {
//            apiResultServiceResult.setSuccess(Boolean.FALSE);
//            apiResultServiceResult.setMessage(ServiceResult.UPDATE_FAIL);
//            return apiResultServiceResult;
//        }
        UpdateWrapper<Banner> bannerUpdateWrapper = new UpdateWrapper<>();
        bannerUpdateWrapper.eq("id", bennerVo.getId());
        Banner benner = new Banner();
        benner.setName(bennerVo.getName());//名称
        benner.setPicturePath(bennerVo.getPicturePath());//图片路径
        benner.setSize(bennerVo.getSize());//尺寸
        benner.setAvailable(bennerVo.getAvailable());//状态
//        benner.setSecondaryPagePath(bennerVo.getSecondaryPagePath());//二级页面目录
        benner.setModifierId(bennerVo.getModifierId());//修改人id
        benner.setUpdateTime(new Date());
        bannerMapper.update(benner, bannerUpdateWrapper);
        apiResultServiceResult.setSuccess(Boolean.TRUE);
        apiResultServiceResult.setMessage(ServiceResult.UPDATE_SUCCESS);
        return apiResultServiceResult;
    }

    /**
     * 通过id主键删除Banner
     * @param id
     * @return
     */
    @Override
    public void deleteBanner(Long id) throws SftpException {
//        //通过主键查询数据
//        Banner banner = bannerMapper.selectById(id);
//        //获取图片路径
//        String img = banner.getPicturePath();
//        String[] split = img.split(FtpModule.FTP_NAME);
//        int index = split[1].lastIndexOf("/");
//        //图片位置
//        String imgUrl = FtpModule.FTP_NAME + split[1].substring(0, index);
//        //图片名称
//        String imgName = split[1].substring(index + 1);
//        //连接ftp 进行删除图片
//        SftpUtils sftp = new SftpUtils(ftpAccountConfig.getUsername(), ftpAccountConfig.getPassword(), ftpAccountConfig.getHost(), ftpAccountConfig.getPort());
//        sftp.login();
//        sftp.delete(ftpAccountConfig.getImageSaveBasePath() + imgUrl, imgName);
//        sftp.logout();
//        log.info("当前正在删除的图片:" + ftpAccountConfig.getImageSaveBasePath() + imgUrl + imgName);
//        //进行清除数据记录
         baseMapper.deleteById(id);
    }

    /**
     * Bannner列表
     * @param bennerVo
     * @return
     */
    @Override
    public void updateAvailable(BennerVo bennerVo) {
        UpdateWrapper<Banner> bannerUpdateWrapper = new UpdateWrapper<>();
        bannerUpdateWrapper.eq("id", bennerVo.getId());
        Banner banner = new Banner();
        banner.setAvailable(bennerVo.getAvailable());
        bannerMapper.update(banner, bannerUpdateWrapper);
    }

//    /**
//     * ftp上传、编辑、图片
//     *
//     * @return
//     */
//    public UploadVideoPojo ftpImg(String type, BennerVo bennerVo) throws IOException, SftpException {
//        MultipartFile file = bennerVo.getFile();
//        String originalFileName = file.getOriginalFilename();
//        InputStream input = file.getInputStream();
//        // 生成新的文件名
//        String fileExt = PathUtils.getFileExtension(originalFileName);
//        String newFileName = getRandomFileName();
//        if (!fileExt.isEmpty()) {
//            newFileName += "." + fileExt;
//        }
//
//        // 获取年月日字符串
//        Calendar now = Calendar.getInstance();
//        String year = Integer.toString(now.get(Calendar.YEAR));
//        String month = Integer.toString(now.get(Calendar.MONTH) + 1);
//        month = StringUtils.padRight(month, 2, '0');
//        String day = Integer.toString(now.get(Calendar.DAY_OF_MONTH));
//        day = StringUtils.padRight(day, 2, '0');
//
//        // 相对路径名
//        String relativeDirName = FtpModule.FTP_NAME + "/" + year + "/" + month + "/" + day; // 前后都已有斜杠
//
//        if (type.equals(FtpModule.FTP_UPDATE)) {
//            //通过id去查询对应的旧的url图片
//            Banner banner = bannerMapper.selectById(bennerVo.getId());
//            //获取路径
//            String img = banner.getPicturePath();
//            String[] split = img.split(FtpModule.FTP_NAME);
//            int index = split[1].lastIndexOf("/");
//            //图片位置
//            String imgUrl = FtpModule.FTP_NAME + split[1].substring(0, index);
//            //图片名称
//            String imgName = split[1].substring(index + 1);
//            // 传ftp
//            SftpUtils sftp = new SftpUtils(ftpAccountConfig.getUsername(), ftpAccountConfig.getPassword(), ftpAccountConfig.getHost(), ftpAccountConfig.getPort());
//            sftp.login();
//            sftp.delete(ftpAccountConfig.getImageSaveBasePath() + imgUrl, imgName);
//            sftp.upload(ftpAccountConfig.getImageSaveBasePath() + relativeDirName, newFileName, input);
//            sftp.logout();
//        } else {
//            // 传ftp
//            SftpUtils sftp = new SftpUtils(ftpAccountConfig.getUsername(), ftpAccountConfig.getPassword(), ftpAccountConfig.getHost(), ftpAccountConfig.getPort());
//            sftp.login();
//            sftp.upload(ftpAccountConfig.getImageSaveBasePath() + relativeDirName, newFileName, input);
//            sftp.logout();
//        }
//        UploadVideoPojo result = new UploadVideoPojo();
//        result.setOriginalFileName(originalFileName);
//        result.setRelativeUrl(relativeDirName + "/" + newFileName);
//        result.setAbsoluteUrl(ftpAccountConfig.getImageUrlBasePath() + relativeDirName + "/" + newFileName);
//        return result;
//    }
//
//    /**
//     * //     * 获取随机文件名
//     * //     *
//     * //     * @return
//     * //
//     */
//    private String getRandomFileName() {
//        String guid = java.util.UUID.randomUUID().toString().replace("-", "");
//
//        Date date = new Date(System.currentTimeMillis());
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
//        String timeString = simpleDateFormat.format(date);
//
//        StringBuilder sb = new StringBuilder();
//        sb.append(timeString).append("-").append(guid);
//        return sb.toString();
//    }
}